package com.amado.course34Thread;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2018/7/18.
 */
public class S06SynchronizedCodeTest {
    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static Integer lockVar =1;
    //锁没在方法上面？锁谁
    public static void test(int i) {
    	//一定是串行的，先获取锁，得到锁后再进入方法执行代码，如果没有锁则等待锁,执行完代码后自动释放锁
    	//锁lockVar变量
        synchronized (lockVar) {
            System.out.println(Thread.currentThread().getName() + " " + simpleDateFormat.format(new Date()) + " " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //这个代码可以并行
        System.out.println("sdafasd");
    }

    public static void main(String[] args) {
    	//java 8以前写法
        new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 5; i++) {
	                S06SynchronizedCodeTest.test(i);
	            }
			}
		}).start();
        //java 8写法
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                S06SynchronizedCodeTest.test(i);
            }
        }).start();
    }
}

